package com.itboye.hutouben.activity.luntan;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itboye.hutouben.R;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.base.MyApplcation;
import com.itboye.hutouben.bean.UplodeImg;
import com.itboye.hutouben.photo.CopyOfPhotoActivity;
import com.itboye.hutouben.presenter.LunTanPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.GlideLoader;
import com.itboye.hutouben.util.MultipartRequest;
import com.itboye.hutouben.util.MyGongJv;
import com.itboye.hutouben.util.XImageLoader;
import com.itboye.hutouben.volley.ResultEntity;
import com.itboye.hutouben.widget.XGridView;
import com.itboye.hutouben.widget.chatemoji.FaceInputView;
import com.itboye.hutouben.widget.chatemoji.Spanned2String;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.hutouben.util.SPUtils.getSp;

/**
 * 帖子发表
 */
public class TieZiWriteActivity extends BaseActivity implements Observer {
    ImageView close_icon;
    TextView add_shap_title_tv;
    EditText et_title, et_content;
    ToggleButton toggle_pinglun, toggle_zhiding;
    TextView fatie_ok;

    String pinglun = "0", zhiding = "0";//限制回复和置顶

    XGridView noScrollgridview;
    public static List<String> listImg = new ArrayList<String>();//保存图片
    GridAdapter adapters;
    protected StringBuffer imgBuffer = new StringBuffer();//上传成功的图片id
    int i = 0;
    String uid;
    LunTanPresenter presenter;

    ImageView emoji;//表情按钮

    LinearLayout faceInputContainer;//表情显示布局
    private FaceInputView faceInputView;//表情

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tiezi_write);
        add_shap_title_tv.setText("写论坛");
        uid = getSp(TieZiWriteActivity.this, Const.ID);
        presenter = new LunTanPresenter(this);
        faceInputView = new FaceInputView(this);
        faceInputContainer.addView(faceInputView);
        faceInputView.setOnClickListener(new FaceInputListenr());
        noScrollgridviews();
    }
    private class FaceInputListenr implements FaceInputView.OnFaceClickListener {

        @Override
        public void selectedFace(FaceInputView.Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = et_content.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = et_content.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                et_content.append(Html.fromHtml("<img src='" + id + "'/>",
                        imageGetter, null));// 添加表情
            }
        }

    }

    // 输入表情需要
    Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            @SuppressWarnings("deprecation")
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        adapters = new GridAdapter(TieZiWriteActivity.this);
        noScrollgridview.setAdapter(adapters);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (listImg != null) {
            listImg.clear();
        }
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.emoji:
                if (faceInputContainer.getVisibility()== View.VISIBLE){
                    faceInputContainer.setVisibility(View.GONE);
                    fatie_ok.setVisibility(View.VISIBLE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                }else{
                    faceInputContainer.setVisibility(View.VISIBLE);
                    fatie_ok.setVisibility(View.GONE);
                    emoji.setBackgroundResource(R.drawable.jianpan);
                }
                MyGongJv.yincang(v);
                break;
            case R.id.et_content:
                if (faceInputContainer.getVisibility()== View.VISIBLE){
                    faceInputContainer.setVisibility(View.GONE);
                    fatie_ok.setVisibility(View.VISIBLE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                }
                break;
            case R.id.close_icon:
                finish();
                // ByAlert.alert(pinglun+";"+zhiding);
                break;
            case R.id.fatie_ok:

                String title = et_title.getText().toString().trim();
                String content = et_content.getText().toString().trim();
                if (title.equals("")) {
                    ByAlert.alert("请填写标题");
                    return;
                }
                if (content.equals("")) {
                    ByAlert.alert("请填写内容");
                    return;
                }
                fatie_ok.setClickable(false);
                showProgressDialog("请稍后...", true);
                List<File> files = new ArrayList<File>();
                for (i = 0; i < listImg.size(); i++) {
                    File file = new File(listImg.get(i));
                    files.add(file);
                }
                if (files.size() <= 0) {
                 //   ByAlert.alert("请上传图片");
                    presenter.fatie(uid, title, Spanned2String.parse(et_content.getText()), "", pinglun, zhiding, "android_driver");
                    return;
                }
                Map<String, String> params = new HashMap<String, String>();
                params.put("uid", uid);
                params.put("type", "other");
                MultipartRequest multipartRequest = new MultipartRequest(
                        Const.IMAGE_URL,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String arg0) {
                                // TODO Auto-generated method stub
                                String code = "";
                                String result = "";
                                try {
                                    closeProgressDialog();
                                } catch (Exception e) {

                                }
                                try {
                                    JSONObject jsonObject = new JSONObject(arg0);
                                    code = jsonObject.getString("code");
                                    result = jsonObject.getString("data");
                                    if (code.equals("-1")) {
                                        ByAlert.alert(result);
                                    } else {
                                        Gson gson = new Gson();
                                        Type type = new TypeToken<UplodeImg>() {
                                        }.getType();
                                        Log.v("msg", result + "多图上传");
                                        UplodeImg beans = gson.fromJson(arg0, type);
                                        for (UplodeImg.Dates bean : beans.getData()) {
                                            imgBuffer.append(bean.getId() + ",");
                                        }
                                        String tid="";
                                        if (imgBuffer.length()>0){
                                            tid = imgBuffer.substring(0, imgBuffer.length() - 1);
                                        }
                                        String title = et_title.getText().toString().trim();
                                        String content = et_content.getText().toString().trim();
                                        presenter.fatie(uid, title, Spanned2String.parse(et_content.getText()), tid, pinglun, zhiding,Const.APP_FOR);

                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        // TODO Auto-generated method stub
                        ByAlert.alert(arg0);
                        closeProgressDialog();
                        fatie_ok.setClickable(true);
                    }
                }, "image[]", files, params);
                MyApplcation.addRequest(multipartRequest);
                break;
        }
    }

    //操作gridview
    private void noScrollgridviews() {
        noScrollgridview = (XGridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == listImg.size()) {
                    pic();
                } else {
                    Intent intent = new Intent(TieZiWriteActivity.this,
                            CopyOfPhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    intent.putExtra("type", 2);
                    startActivityForResult(intent, 101);
                }
            }
        });
        adapters = new GridAdapter(TieZiWriteActivity.this);
        noScrollgridview.setAdapter(adapters);
        //评论的ToggleButton点击
        toggle_pinglun.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    pinglun = "1";
                } else {
                    pinglun = "0";
                }
            }
        });
        //置顶的ToggleButton点击
        toggle_zhiding.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    zhiding = "1";
                } else {
                    zhiding = "0";
                }
            }
        });
    }

    /**
     * 打开图库
     */
    private void pic() {
        ImageConfig imageConfig
                = new ImageConfig.Builder(new GlideLoader())
                .steepToolBarColor(getResources().getColor(R.color.blue))
                .titleBgColor(getResources().getColor(R.color.blue))
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启多选   （默认为多选）
                .mutiSelect()
                // 多选时的最大数量   （默认 9 张）
                .mutiSelectMaxSize(9 - listImg.size())
                // 开启拍照功能 （默认关闭）
                .showCamera()
                // 已选择的图片路径
                // .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                .filePath("/ImageSelector/Pictures")
                .build();

        ImageSelector.open(TieZiWriteActivity.this, imageConfig);   // 开启图片选择器
        requestPermission(new String[]{Manifest.permission.CAMERA}, 0x0003);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {

            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            for (String path : pathList) {
                Log.i("ImagePathList", path);
                if (listImg.size() < 9) {
                    listImg.add(path);
                }
            }
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (!entity.getCode().equals("0")) {
                ByAlert.alert(entity.getMsg());
                return;
            }
            //发帖子
            if (entity.getEventType() == LunTanPresenter.fatie_success) {
                ByAlert.alert(entity.getData());
                finish();

            } else if (entity.getEventType() == LunTanPresenter.fatie_fail) {
                ByAlert.alert(entity.getData());
                fatie_ok.setClickable(true);
            }
        }

    }

    /**
     * gridView适配器
     */
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return (listImg.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == listImg.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                XImageLoader.load("file://" + listImg.get(position),
                        holder.image);
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
    }
}
